package com.tutu.common.util;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class GroovyScript implements BeanPostProcessor {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private Binding binding = new Binding();
	
	public GroovyScript() {}
	public void execute(String script, Map<String, Object> vars){
		executeObject(script, vars);
	}
	private void setParameters(GroovyShell shell, Map<String, Object> vars){
		if (vars == null) return;
		Set<Map.Entry<String, Object>> set = vars.entrySet();
		for (Iterator<Map.Entry<String, Object>> it = set.iterator(); it.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry)it.next();
			shell.setVariable((String)entry.getKey(), entry.getValue());
		}
	}
	public Object executeObject(String script, Map<String, Object> vars){
		logger.debug("执行:" + script);
		GroovyShell shell = new GroovyShell(this.binding);
		setParameters(shell, vars);
		script = script.replace("&apos;", "'").replace("&quot;", "\"").replace("&gt;", ">").replace("&lt;", "<").replace("&nuot;", "\n").replace("&amp;", "&");
		Object rtn = shell.evaluate(script);
		binding.getVariables().clear();
		return rtn;
	}
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		boolean isImplScript = BeanUtils.isInherit(bean.getClass(), IScript.class);
		if (isImplScript) {
			this.binding.setProperty(beanName, bean);
		}
		return bean;
	}
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}
}
